#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright © 2005-2007 Kaufmann Manuel
#
# This file is part of Tweety-Finger.
#
# Tweety-Finger is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Tweety-Finger is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Tweety-Finger; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  
# USA

import os

class HighScores(object):
	def __init__(self, listScoresFiles, scoreFont, window):
		"""
			Inicializador de la clase
		"""
		
		self.window = window
		self.scoresFiles = listScoresFiles
		self.scoreFont = scoreFont
		
		self.scores = {}
		for score in self.scoresFiles:
			self.scores[score] = []
		
		self.fileScores = {"Easy":"data/scoresEasy.dat",\
			  "Medium":"data/scoresMedium.dat",\
			  "Hard":"data/scoresHard.dat"}
		
		self.position = 0
		self.checkFile()
		self.getScores()
		
	def checkFile(self):
		"""
			Chequea si existe el archivo, si no existe lo crea
			con los puntajes dummy
		"""
		
		for score in self.scoresFiles:
			if os.path.isfile(score):
				pass
			else:
				self.initializeScoresFile(score)

	def initializeScoresFile(self, filename):
		"""
			Inicializa el archivo de datos a los scores dummy
		"""
		
		scoreFile = open(filename, "w")
		dummyScores = ["01|Cat|5",
				"02|Tat|10",
				"03|PaL|15",
				"04|Sus|20",
				"05|Dab|30",
				"06|Gam|35",
				"07|Dtl|40",
				"08|Tub|45",
				"09|Vir|55",
				"10|Die|60"]
		for score in dummyScores:
			scoreFile.write(score + "\n")
		scoreFile.close()

	def getScores(self):
		"""
			Carga los scores en el diccionario self.scores
		"""
		
		for filename in self.scoresFiles:
			scoreFile = open(filename, "r")
			
			for line in scoreFile.readlines():
				line = line.strip("\n").split("|")
				self.scores[filename].append(line)
			scoreFile.close()

	def saveScores(self):
		"""
			Guarda los scores que se encuentran en el diccionario
			a los archivos correspondientes
		"""
		
		filename = self.fileScores[self.difficulty]
		
		position = 1
		scoreFile = open(filename, "w")
		for score in self.scores[filename]:
			scoreFile.write("%02d|%s|%s\n" % (position, \
						score[1], score[2]))
			position += 1
		scoreFile.close()
		self.getScores()

	def isHighScore(self, time):
		"""
			Verifica si el tiempo pasado es un highscore
		"""
		
		for score in self.scores[self.fileScores[self.difficulty]]:
			if time < float(score[2]):
				self.position = int(score[0])
				return True
		return False

	def insertHighScore(self, time, name):
		"""
			Inserta el highscore en el archivo
		"""
		
		if self.isHighScore(time):
			self.scores[self.fileScores[self.difficulty]].pop(-1)
			self.scores[self.fileScores[self.difficulty]].insert(self.position-1, \
					[str(self.position),
					name, str(time)])
			self.saveScores()

	def showHighScores(self, option):
		"""
			Muestra los high scores en la pantalla que corresponden
			a la dificultad opcion
		"""
		
		self.window.setTitle("High Scores")

		for score in self.scores[self.fileScores[option]]:
			self.window.showOnePosition(score[0],score[1], score[2], self.scoreFont)
		self.window.resetHighScorePosition()
